#include <stdio.h>

int maxArea(int *height, int heightSize)
{
    int left = 0, right = heightSize - 1;
    int left_max = 0, right_max = 0;
    int res = 0;
    while (left < right)
    {
        if (height[left] < height[right])
        {
            if (height[left] >= left_max)
            {
                left_max = height[left];
            }
            else
            {
                res += left_max - height[left];
            }
            left = left + 1;
        }
        else
        {
            if (height[right] >= right_max)
            {
                right_max = height[right];
            }
            else
            {
                res += right_max - height[right];
            }
            right = right - 1;
        }
    }
    return res;
}

int main()
{
    int t;
    scanf("%d", &t);
    int height[300000] = {0};
    int i;
    for (i = 0; i < t; i++)
    {
        scanf("%d", &height[i]);
    }
    int lable = 0;
    int area = 0;
    for(i = 0; i < t; i++){
        if(height[i] == 0){
            area += maxArea(height + lable, i - lable);
            lable = (i+1);
        }
        if(i == (t - 1) && height[i] != 0){
            area += maxArea(height + lable, i - lable + 1);
        }
    }
    printf("%d\n", area);

    return 0;
}
